package com.ldr.danmuku

import android.animation.ValueAnimator
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.animation.LinearInterpolator
import androidx.annotation.MainThread
import java.lang.ref.WeakReference

/**
 * @author :create by ldr
 * time:2022/12/29 10:34
 * @descript:泳道管理类
 */
class LanViewManager {

    companion object{
        val singleton:LanViewManager by lazy(LazyThreadSafetyMode.NONE){
            LanViewManager()
        }
    }

    val mDanMuConfig = DanMuManager.singleton.mDanMuConfig

    private val mDanMuLaneViewArrayList = ArrayList<DanMuLaneView>()

    val mHandler = LanViewHandler()

    var mValueAnimator:ValueAnimator?=null

    init {

    }

    /**
     * 设置弹幕泳道的list
     */
    fun setLanViewList(danMuLaneViewArrayList:ArrayList<DanMuLaneView>){
        mDanMuLaneViewArrayList.clear()
        mDanMuLaneViewArrayList.addAll(danMuLaneViewArrayList)
    }

    fun clearLanView(){
        mDanMuLaneViewArrayList.clear()
    }
    /**
     * 增加泳道
     */
    fun addLanView(danMuLaneView:DanMuLaneView) {
        mDanMuLaneViewArrayList.add(danMuLaneView)
    }

    /**
     * 开始动画
     */
    fun startAnimal(){
        if (mDanMuLaneViewArrayList.isEmpty()){
            Log.d("Danmu", "startAnimal: ")
            return
        }
        ValueAnimator.setFrameDelay(16)
        mValueAnimator = ValueAnimator.ofFloat(1.0f).apply {
            duration = mDanMuConfig.mDanMUItemSpeed.toLong()
            interpolator = LinearInterpolator()

            repeatCount = ValueAnimator.INFINITE //无限制
            addUpdateListener {
                mDanMuLaneViewArrayList.forEach {
                    it.updateViewLayout()
                }
            }
        }
    }

    /**
     * 释放动画
     */
    fun releaseAnimal(): Unit {
        mValueAnimator?.removeAllListeners()
        mValueAnimator?.end()
    }

    fun onPause(): Unit {
        mValueAnimator?.pause()
    }

    fun onResume(): Unit {
        mValueAnimator?.resume()
    }


    inner class LanViewHandler : Handler(Looper.getMainLooper()){

        var mDanMuLaneViewArrayListWeakReference:WeakReference<ArrayList<DanMuLaneView>>?= null

        fun setDanMuLanList(danMuLaneViewArrayList:ArrayList<DanMuLaneView>){
            mDanMuLaneViewArrayListWeakReference = WeakReference(danMuLaneViewArrayList)
        }

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)

        }
    }


}